package com.mdd.maduoduo.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

import com.mdd.maduoduo.R;
import com.mdd.maduoduo.activity.MaxActivity;
import com.mdd.maduoduo.activity.ShareCodeActivity;
import com.mdd.maduoduo.constants.CommonConstants;
import com.mdd.maduoduo.entity.BannerEntity;
import com.mdd.maduoduo.entity.UserEntity;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Utils {
    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    public static void startWeb(Context context, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

// 检查是否有Activity可以处理这个Intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        } else {
            // 没有可用的浏览器
            ToastUtils.showLongToast(context, "没有可用的浏览器");
        }
    }

    public static void jump(Context context,UserEntity.DataDTO.FunctionConfigDtosDTO.ItemDtosDTO bean){
        IWXAPI api = WXAPIFactory.createWXAPI(context, CommonConstants.WX_APPID, true);
        switch (bean.jumpType){
            case 0:
                startWeb(context,bean.jumpUrl);
                break;
            case 2:
                //分享
                //初始化一个WXWebpageObject，填写url
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl =bean.shareConfigMap.shareUrl;
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = bean.shareConfigMap.shareTitle;
                msg.description =bean.shareConfigMap.shareSologn;
                Bitmap thumbBmp = BitmapFactory.decodeResource(context.getResources(), R.mipmap.app_logo);
                msg.thumbData =Utils.bitmapToByteArray(thumbBmp,Bitmap.CompressFormat.JPEG, 80);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = "webpage" + System.currentTimeMillis(); // 唯一标识
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;
                api.sendReq(req);
                break;
            case 4:
                //跳转max会员
                context.startActivity(new Intent(context, MaxActivity.class));
                break;
            case 6:
                //跳转小程序
                WXLaunchMiniProgram.Req reqProgram = new WXLaunchMiniProgram.Req();
                reqProgram.userName = "gh_295070a469f4"; // 填小程序原始id
                reqProgram.path = "pages/index/index";                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                reqProgram.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                api.sendReq(reqProgram);
                break;
            case 7:
                //跳转客服
                String phoneNumber = bean.jumpUrl; // 要拨打的电话号码
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + phoneNumber));
                context.startActivity(intent);
                break;
            case 8:
                ClipeBoardUtil.setClipeBoardContent(context,bean.jumpUrl);
                ToastUtils.showLongToast(context,"复制成功");
                //展示 点击可以复制
//                            Utils.startWeb(getActivity(),bean.jumpUrl);
                break;
            case 9:
                //跳转多人共享界面
//                            Utils.startWeb(getActivity(),bean.jumpUrl);
                break;
        }
    }

    /**
     * 将Bitmap转换为字节数组
     * @param bitmap 要转换的Bitmap对象
     * @param format 图片格式(Bitmap.CompressFormat.JPEG/PNG/WEBP)
     * @param quality 压缩质量(0-100)
     * @return 字节数组
     */
    public static byte[] bitmapToByteArray(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(format, quality, outputStream);
        byte[] byteArray = outputStream.toByteArray();
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArray;
    }

    /**
     * 从URL下载图片并转换为byte[]
     * @param imageUrl 图片URL
     * @return 图片的字节数组
     */
    public static byte[] downloadImageAndConvertToByteArray(String imageUrl) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;

        try {
            // 1. 创建URL对象
            URL url = new URL(imageUrl);

            // 2. 打开连接
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();

            // 3. 获取输入流
            inputStream = connection.getInputStream();

            // 4. 读取流并转换为byte[]
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }

            // 5. 返回字节数组
            return byteArrayOutputStream.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 6. 关闭流和连接
            try {
                if (inputStream != null) inputStream.close();
                if (byteArrayOutputStream != null) byteArrayOutputStream.close();
                if (connection != null) connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void jumpOther(Context context, BannerEntity.DataDTO.FunctionConfigDtosDTO.ItemDtosDTO bean){
        switch (bean.jumpType){
            case 0:
                startWeb(context,bean.jumpUrl);
                break;
            case 2:
                //分享
//                            Utils.startWeb(getActivity(),bean.jumpUrl);
                break;
            case 4:
                //跳转max会员
                context.startActivity(new Intent(context, MaxActivity.class));
                break;
            case 6:
                //跳转小程序
//                            Utils.startWeb(getActivity(),bean.jumpUrl);
                break;
            case 7:
                //跳转客服
                String phoneNumber = bean.jumpUrl; // 要拨打的电话号码
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + phoneNumber));
                context.startActivity(intent);
                break;
            case 8:
                ClipeBoardUtil.setClipeBoardContent(context,bean.jumpUrl);
                ToastUtils.showLongToast(context,"复制成功");
                break;
            case 9:
                //跳转多人共享界面
                context.startActivity(new Intent(context,ShareCodeActivity.class));
                break;
        }
    }
}
